package com.lagou.niancheng.core.result;

import com.lagou.niancheng.core.config.MappedStatement;
import com.lagou.niancheng.core.config.ResultTypeMetaData;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * com.lagou.niancheng.core.result.DefaultResultConverter
 *
 * @author 大犬
 * @date 2020/3/27
 */
public class DefaultResultSetConverter implements ResultSetConverter {

    @Override
    public List<Object> converter(MappedStatement statement, ResultSet resultSet) throws Exception {
        ResultTypeMetaData resultTypeMetaData = statement.getResultTypeMetaData();
        Class resultType = resultTypeMetaData.getResultType();
        Map<String, Field> fieldMap = resultTypeMetaData.getFieldMap();
        ArrayList<Object> objects = new ArrayList<>();
        // 6. 封装返回结果集
        while (resultSet.next()) {
            Object result = resultType.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);
                String lowerCaseColumn = columnName.replaceAll("_", "").toLowerCase();
                Field field = fieldMap.get(lowerCaseColumn);
                if (field != null) {
                    field.set(result, value);
                }
            }
            objects.add(result);

        }
        return objects;
    }

}
